package 算法.线性表;

import java.util.Scanner;

public class 迷宫 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入迷宫大小m x n:");
        String[] k = in.nextLine().split("x");
        Integer m = Integer.parseInt(k[0]);
        Integer n = Integer.parseInt(k[1]);
        String[][] map = new String[m][n];
        Initial(map, m, n); // 初始化迷宫
        //map[1][1] = "->";
        map[m-2][n-2] = "->";
        String[][] wall = SetWall(map, m, n, in);// 设置障碍
        // 迷宫遍历
        GetWay(map,1,1);
        PutMap(map,m,n);

    }

    private static boolean GetWay(String[][] map, int i, int j) {
        //
        if (map[i][j].equals("*"))
            return true;
        else{
            if (map[i][j].equals(" ")){
                map[i][j] ="X";
                if (GetWay(map,i+1,j)){
                    return true;
                }else if (GetWay(map,i,j+1)){
                    return true;
                }else if (GetWay(map,i-1,j)){
                    return true;
                }else if (GetWay(map,i,j-1)){
                    return true;
                }else {
                    map[i][j]= "X";
                    return false;
                }
            }else {
                return false;
            }

        }


    }

    private static String[][] SetWall(String[][] map, Integer m, Integer n, Scanner in) {
        int k = 1;
        while (k<n-2) {
            System.out.println("请设置"+k+"行障碍：i1,i2,i3...，结束:end");
            String line = in.nextLine();
            if (line.equals("end"))
                break;
            String[] wall = line.split(",");
            for (int i = 0; i < wall.length; i++) {
                Integer j = Integer.parseInt( wall[i]);
                if (0<=j&&j<n)
                    map[k][j] = "+";
                else
                    System.out.println("输入不合法");
            }
            PutMap(map, m, n);
            k++;
        }
        return map;
    }

    private static void PutMap(String[][] map, int m, int n) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(map[i][j]);
            }
            System.out.println();
        }
    }

    private static void Initial(String[][] map, int m, int n) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                (map[i][j]) = " ";
            }
        }
        for (int i = 0; i < m; i++) {
            map[i][0] = "+"; // 1 代表墙
            map[i][n - 1] = "+"; // 1 代表墙
        }
        for (int i = 0; i < n; i++) {
            map[0][i] = "+"; // 1 代表墙
            map[m - 1][i] = "+"; // 1 代表墙
        }
    }
}
